﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CE.User;
using CE.HomeLoan;
using CE.Global;
using CE.Mail;
using CE.Company;
using CE.Database;

public partial class home_loan_personal_details : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {

        }
        else
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Customer))
            {
                ShowUserDetails();
            }
        }

        if (!Page.IsPostBack)
        {
            txtFullName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtFullName.ClientID + "','" + rfvFullName.ClientID + "','" + revFullName.ClientID + "');");
            //txtLastName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtLastName.ClientID + "','" + rfvLastName.ClientID + "','" + revLastName.ClientID + "');");
            txtEmailAddress.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmailAddress.ClientID + "','" + rfvEmailAddress.ClientID + "','" + revEmailAddress.ClientID + "');");
            if (Session[General.HLId] != null)
            {
                //ShowHFLoan();
            }
            else
            {
                Response.Redirect("home-loan.aspx");
            }
            General.ClearAllSession(this.Page, "HL");
            Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
        }
    }

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        ChangeValidationEffectServerSide("homeloan");
        if (Page.IsValid)
        {
            Int64 _result = 0;
            HomeLoan _homeloan = new HomeLoan();
            HomeLoanDB _homeloandb = new HomeLoanDB();
            _homeloan.HLId = Convert.ToInt64(Session[General.HLId].ToString());
            _homeloan.StepId = 3;
            _homeloan.FullName = txtFullName.Text;
            //_homeloan.LastName = txtLastName.Text;
            _homeloan.ContactNo = txtContactnumber.GetPhoneNo();
            _homeloan.Email = txtEmailAddress.Text;
            //if (Session[General.UserId] != null)
            //{
            //    _homeloan.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
            //}
            //else
            //{
            //    _homeloan.RefCEUserId = 0;
            //}

            if (Session[General.UserId] == null)
            {
                _homeloan.RefCEUserId = CheckAndCreateAndSendMailToUser();
            }
            else
            {
                _homeloan.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                SendMailToUser(_homeloan.RefCEUserId, true, Session[General.UserEmail].ToString(), Session[General.UserName].ToString(), "");
            }

            if (Session[General.UserId] != null)
            {
                _homeloan.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
            }
            else
            {
                _homeloan.ViewedDetailId = 0;
            }
            _homeloan.Status = true;
            _result = _homeloandb.Insert(_homeloan);
            if (_result > 0)
            {
                Response.Redirect("results.aspx");
            }
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Full Name
        if (rfvFullName.Enabled && rfvFullName.ValidationGroup == strValidationGroup)
        {
            rfvFullName.Validate();
            if (rfvFullName.IsValid == false)
            {
                txtFullName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtFullName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtFullName.ControlStyle.CssClass = "";
        }

        if (revFullName.Enabled && revFullName.ValidationGroup == strValidationGroup)
        {
            if (rfvFullName.IsValid)
            {
                revFullName.Validate();
                if (revFullName.IsValid == false)
                {
                    txtFullName.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtFullName.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtFullName.ControlStyle.CssClass = "";
        }

        ////Last Name
        //if (rfvLastName.Enabled && rfvLastName.ValidationGroup == strValidationGroup)
        //{
        //    rfvLastName.Validate();
        //    if (rfvLastName.IsValid == false)
        //    {
        //        txtLastName.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        txtLastName.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    txtLastName.ControlStyle.CssClass = "";
        //}

        //if (revLastName.Enabled && revLastName.ValidationGroup == strValidationGroup)
        //{
        //    if (rfvLastName.IsValid)
        //    {
        //        revLastName.Validate();
        //        if (revLastName.IsValid == false)
        //        {
        //            txtLastName.ControlStyle.CssClass = "validationError";
        //        }
        //        else
        //        {
        //            txtLastName.ControlStyle.CssClass = "";
        //        }
        //    }
        //}
        //else
        //{
        //    txtLastName.ControlStyle.CssClass = "";
        //}

        //Contactnumber
        txtContactnumber.ChangeValidationEffectServerSide(strValidationGroup);

        //Email Address
        if (rfvEmailAddress.Enabled && rfvEmailAddress.ValidationGroup == strValidationGroup)
        {
            rfvEmailAddress.Validate();
            if (rfvEmailAddress.IsValid == false)
            {
                txtEmailAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtEmailAddress.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtEmailAddress.ControlStyle.CssClass = "";
        }

        if (revEmailAddress.Enabled && revEmailAddress.ValidationGroup == strValidationGroup)
        {
            if (rfvEmailAddress.IsValid)
            {
                revEmailAddress.Validate();
                if (revEmailAddress.IsValid == false)
                {
                    txtEmailAddress.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtEmailAddress.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtEmailAddress.ControlStyle.CssClass = "";
        }
    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("HL", Request, "Home loan rate and loan tenure details.");
    }

    private void CheckValidation()
    {
        txtFullName.Text = General.ClearScriptTag(txtFullName.Text);
        //txtLastName.Text = General.ClearScriptTag(txtLastName.Text);
        txtEmailAddress.Text = General.ClearScriptTag(txtEmailAddress.Text);
    }

    private void ShowUserDetails()
    {
        if (Session[CE.Global.General.UserId] != null)
        {
            txtContactnumber.PhoneNo = Session[CE.Global.General.UserPhoneNo].ToString();
            txtEmailAddress.Text = Session[CE.Global.General.UserEmail].ToString();
        }
        else
        {
            txtEmailAddress.Text = "";
        }
    }

    private Int64 CheckAndCreateAndSendMailToUser()
    {
        Int64 _retVal = 0;
        Account _account = new Account();
        AccountDB _accountdb = new AccountDB();

        if (!_accountdb.IsAlreadyExist(txtEmailAddress.Text, Convert.ToInt32(CE.Global.CEUserType.Customer)))
        {
            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();
            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            long _result = -1;

            _account.Email = txtEmailAddress.Text.ToLower();
            Random _random = new Random();
            string _authcode = "";
            _authcode = "H" + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();
            _account.AuthCode = _authcode;

            _account.UserId = "CEUSERAUTOIDHL";
            _account.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
            _account.IsAcceptTC = true;
            _account.Status = true;
            _account.RefCEUserID = -1;

            _result = _accountdb.Insert(_account);
            _account.CEID = _result;

            _retVal = _result;

            if (_result > 0)
            {
                //_userprofile.FirstName = Server.HtmlEncode(txtFullName.Text);
                _userprofile.SurName = Server.HtmlEncode(txtFullName.Text);
                _userprofile.DOB = new DateTime(1900, 1, 1);
                _userprofile.RefCEUserId = _account.CEID;
                _userprofile.Status = "NEW";
                _result = _userprofiledb.Insert(_userprofile);

                _contact.Email = _account.Email;
                _contact.Mobile = txtContactnumber.GetPhoneNo();

                _contact.Status = true;
                _contact.RefCEUserId = _account.CEID;
                _result = _contactdb.Insert(_contact);

                if (_result > 0)
                {
                    //Send Email Travel
                    SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                    Session[CE.Global.General.UserId] = _account.CEID;
                    Session[CE.Global.General.UserTypeId] = _account.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _account.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = CE.Global.General.GetUTCDateTime().ToString();
                    if (_userprofile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _userprofile.SurName + " " + _userprofile.FirstName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _userprofile.SurName;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "0";
                    if (!SendMailToUser(_account.CEID, false, txtEmailAddress.Text, Session[CE.Global.General.UserName].ToString(), _authcode))
                    {
                        _account.Info1 = "0";
                        _account.Info2 = "New User - Home Loans";
                        _accountdb.Insert(_account);
                    }
                }
            }
        }
        else
        {
            //Existing Email
            _account = _accountdb.CheckEmail(txtEmailAddress.Text, Convert.ToInt32(CE.Global.CEUserType.Customer));
            if (_account != null)
            {
                if (!SendMailToUser(_account.CEID, true, txtEmailAddress.Text, txtFullName.Text, ""))
                {
                    //_account.Info1 = "0";
                    //_account.Info2 = "First Quote - Home Loans";
                    //_accountdb.Insert(_account);
                }
                _retVal = _account.CEID;
            }
        }

        _account = null;
        _accountdb = null;

        return _retVal;
    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = CE.Global.General.GetUTCDateTime();
        _loghis.EndTime = CE.Global.General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;

            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;

            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            //_loginfo.Info1 = Request.Browser.Tables;
            //_loginfo.Info2 = Request.Browser.Platform;
            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    private bool SendMailToUser(Int64 RefCEUserId, bool IsExistingUser, string EmailAddress, string UserName, string DummyAuthCode)
    {
        bool _retVal = false;
        if (CheckFirstTimeQuote(RefCEUserId))
        {
            //MyMailManager _mailMgr = new MyMailManager();
            string _emailTo = EmailAddress;
            string _customername = UserName;
            string _emailSubject = "First Home Loans Quote - " + CE.Global.General.GetUTCDateTime().ToString();
            string _mailBody = "";
            string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
            string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
            CompanyInformation _company = new CompanyInformation();
            CompanyInformationDB _companydb = new CompanyInformationDB();
            _company = _companydb.GetCompanyInformation(3);
            string _companyAddress = "";
            string _emailaddress = "";
            string _websiteaddress = "";
            if (_company != null)
            {
                _companyAddress = _company.Address1;
                _emailaddress = _company.EmailAddress;
                _websiteaddress = _company.Website;
            }
            _company = null;
            _companydb = null;

            _mailBody = "Dear " + _customername + ", <br /><br />Thank you for using CompareXpress Home Loans Comparison Engine for the first time.";
            if (!IsExistingUser)
            {
                _mailBody = ", <br /><br />Your account has been created — now it will be easier to compare and find the best home loans.";
                _mailBody += "<br /><br />You may now log in to <a href='http://www.comparexpress.com/' target='_blank'>http://www.comparexpress.com/</a> using the following username and password:";
                _mailBody += "<br /><br /> User Name : " + txtEmailAddress.Text;
                _mailBody += "<br /> Password : " + DummyAuthCode;

            }
            _mailBody += "<br /><br />You are able to view this quote through our Members Area by clicking on the link below. <br /><br /> <a href='http://www.comparexpress.com' target='_blank'>http://www.comparexpress.com</a>.";
            _mailBody += "<br /><br /> Enter your Email and Password to login to the Members Area, located on the top right of the page.";

            _mailBody += "<br /><br />If you have any questions, comments, or feedback, please do not hesitate to contact us at <a href='mailto:support@comparexpress.com'>support@comparexpress.com</a>.";
            _mailBody += "<br /><br />Best Regards,<br /><br />Your CompareXpress Team<br/>Customer Support - SG/International";
            _mailBody += "<br /><img src='" + imgLogoUrl + "' />";
            _mailBody += "<br /><hr />";
            _mailBody += _companyAddress;
            _mailBody += "<br /><a href='" + _websiteaddress + "' target='_blank'>" + _websiteaddress + "</a> :: <a href='mailto:" + _emailaddress + "' target='_blank'>" + _emailaddress + "</a><br /><hr />";
            _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";
            if (MyMailManager.SendCRMMessage(_emailTo, _emailSubject, _mailBody))
            {
                _retVal = true;
            }
            else
            {
                _retVal = false;
            }
        }
        else
        {
            _retVal = true;
        }

        return _retVal;
    }

    private bool CheckFirstTimeQuote(Int64 RefCEUserId)
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocAutoEmailFirstQuoteInsertUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@RefCEUserId", RefCEUserId);
        _spList.Add("@EmailType", 300);
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);
        return _retValue == 1;
    }
    
}
